﻿using System.Collections;
using System.Collections.Generic;
using GameCreator.Characters;
using GameCreator.Core;
using UnityEngine;

namespace Gp.GCX {
    [AddComponentMenu("")]
	public class ActionCharacterRotateTowards : IAction
	{
        private static readonly Vector3 PLANE = new Vector3(1, 0, 1);

        public List<Character> characters = new ();
        public TargetPosition target = new TargetPosition();

        // private float duration;
        // private bool wasControllable;

        public override bool InstantExecute(GameObject target, IAction[] actions, int index)
        {

            foreach (var ch in characters) {
                if (ch == null) continue;

                // this.wasControllable = ch.IsControllable();
                // ch.characterLocomotion.SetIsControllable(false);

                Vector3 rotationDirection = (
                    this.target.GetPosition(target) - ch.gameObject.transform.position
                );

                rotationDirection = Vector3.Scale(rotationDirection, PLANE).normalized;
                // this.duration = Vector3.Angle(
                //     ch.transform.TransformDirection(Vector3.forward),
                //     rotationDirection
                // ) / ch.characterLocomotion.angularSpeed;

                ch.characterLocomotion.SetRotation(rotationDirection);
            }
            

			return true;
        }

        // public override IEnumerator Execute(GameObject target, IAction[] actions, int index, params object[] parameters)
        // {
        //
        //     WaitForSeconds wait = new WaitForSeconds(this.duration);
        //     yield return wait;
        //
        //     if (this.cacheCharacter != null)
        //     {
        //         CharacterLocomotion locomotion = this.cacheCharacter.characterLocomotion;
        //         locomotion.SetIsControllable(this.wasControllable);
        //     }
        //     
        //     yield return 0;
        // }

        #if UNITY_EDITOR

        public static new string NAME = "Character/Npc Characters Rotate Towards";
        private const string NODE_TITLE = "Rotate {0} towards {1}";

        public override string GetNodeTitle()
        {
            return string.Format(NODE_TITLE, "characters", this.target);
        }

        #endif
    }
}